var updateApp = function () {

};

// 检查更新
updateApp.checkUpdate = function (apkUrl) {
    //var apkUrl = "http://api2.dhbm.cn/wap/GetVersionAppH5/?key=3414d916c27e14bc3e9e08a30660d5ec268e76d009aee2a2c5a828973f40d223&appid=8880018&flag=com.dhbm.lmsd&encoding=utf-8&resulttype=json";
    //样本 : {"apk":"http://m.dhbm.cn/app/qy/lmsd/an/dhbm.lmsd.1.0.160707.apk","version":"1.0","sub":"160707"}

    if (apkUrl == null) return null;

    var apkVersion = "未可知";
    var apkNameUrl = "";
    var apkName = "";
    var appVersion = "";

    var successCallback = function (response) {
        console.log(response);
        apkVersion = response.version + "." + response.sub;
        apkNameUrl = response.apk;
        console.log("apkName 222 === " + apkNameUrl);
        console.log("apkVersion 222 === " + apkVersion);

        //获取url最后一部分,作为apk 名字
        var x = apkNameUrl.split('/');
        var l = x.length;

        if (l < 1) {
            var sss = "api 返回结果异常,请检查!" + apkNameUrl;
            alert(sss);
            return;
        }

        apkName = x[l - 1];
        console.log("apkName 333 === " + apkName);

        //只有手机上才会继续比较版本号,升级
        // pc上只会执行前面一部分,方便在电脑调试
        if (window.cordova) {
            cordova.getAppVersion.getVersionNumber(function (version) {
                //这是本地打包后 app 版本号,在 config.xml 配置
                console.log("Version 111 === " );
                console.log(version);
                appVersion = version;
                console.log("appVersion 111 === " + appVersion);

                //比较版本号,简单处理:不比较大小,只要不一样,就升级
                if (appVersion < apkVersion) {
                    showUpdateConfirm(apkNameUrl, apkName, appVersion, apkVersion);
                }
            });
        }
        else {
            var sss = "<h4> 当前版本 < " + appVersion + "></h4>";
            sss = sss + "<h4> 网上apk版本 < " + apkVersion + "></h4>";
            alert(sss);
        }
    };

    //首先获取网上 apk 版本号
    $.getJSON(apkUrl, null, successCallback);
};

//以上 供外部调用,以下为私有函数
// 显示是否更新对话框
showUpdateConfirm = function (apkNameUrl, apkName, appVersion, apkVersion) {
    console.log('showUpdateConfirm ====222 ');

    var r = confirm("升级不升级? 1:升级2:不升级", '以后再说,好的');
    if (r) {
        downLoadApk(apkNameUrl, apkName);
    }
};

downLoadApk = function (apkNameUrl, apkName) {
    var url = apkNameUrl;//"http://m.dhbm.cn/app/qy/lmsd/an/dhbm.lmsd.1.0.160707.apk"
    var targetPath = "file:///storage/sdcard0/Download/" + apkName;
    //APP下载存放的路径，可以使用cordova file插件进行相关配置
    var trustAllHosts = true;
    var options = {};
    var downloadProgress = 0;
    var downloadFinished = false;

    console.log('downLoadApk ====333 ');

    //首先放置一个 loading
    var mTitle = "升级提示";
    var mLoadingContent = "正在下载中...";
    var progressLoading = window.navigator.dialogsPlus.progressStart(mTitle, mLoadingContent);
    //progressLoading.setValue(0);

    var ft = new FileTransfer();
    var uri = encodeURI(url);

    if (options && options.timeout !== undefined && options.timeout !== null) {
        $timeout(function () {
            ft.abort();
        }, options.timeout);
        options.timeout = null;
    }
    ;

    ft.onprogress = function (progress) {
        downloadProgress = parseInt((progress.loaded / progress.total) * 100);
        //console.log("downloadProgress ====" + downloadProgress);

        setTimeout(function () {
            progressLoading.setValue(downloadProgress);
        });
    };

    ft.downloadSuccess = function () {
        downloadProgress = 100;
        console.log("downloadProgress 完成====" + downloadProgress);
        progressLoading.hide();
        setTimeout(openAndInstallApk(targetPath), 200);
    };

    ft.downloadFailed = function () {
        var sss = "下载错误!" + JSON.stringify(error);
        alert(sss);
    };

    ft.download(uri, targetPath, ft.downloadSuccess, ft.downloadFailed, trustAllHosts, options);

};

//打开 apk,系统会自动执行安装
openAndInstallApk = function (targetPath) {
    cordova.plugins.fileOpener2.open(targetPath, 'application/vnd.android.package-archive',
    function(){
        // 成功
        console.log("open 成功=== " + targetPath);
    },
    function(){
        // 错误
        var sss = "非法的安装包,请检查!" + err;
        alert(sss);
    });
};
